<?php
namespace app\home\logic;

use app\mingteng\logic\FlashSaleLogic;
use app\mingteng\logic\GroupBuyLogic;
use app\mingteng\logic\PromGoodsLogic;
use app\mingteng\model\Cart;
use app\mingteng\model\MealCart;
use app\mingteng\model\Goods;
use think\Model;
use think\Db;

/**
 * 购物车 逻辑定义
 * Class CatsLogic
 * @package Home\Logic
 */
class CartLogic extends Model
{
    protected $goods;//商品模型
    protected $user_id = 0;//user_id

    public function __construct(){
        parent::__construct();
    }

    /**
     * 包含一个商品模型
     * @param $goods_id
     */
    public function setGoodsModel($goods_id)
    {
        $goodsModel = new Goods();
        $this->goods = $goodsModel::get($goods_id);
    }

    /**
     * 设置用户ID
     * @param $user_id
     */
    public function setUserId($user_id)
    {
        $this->user_id = $user_id;
    }

    /**
     * modify ：addCart
     * @param $goods_num|购买商品数量
     * @param $goods_spec_key|购买商品规格
     * @return array
     */
    public function addGoodsToCart($goods_num, $goods_spec_key, $status=0){
        if(empty($this->goods)){
            return ['status'=>'-3','msg'=>'购买商品不存在','result'=>''];
        }

        $userCartCount = Db::name('cart')->where(['user_id'=>$this->user_id])->count();//获取用户购物车的商品有多少种
        if ($userCartCount >= 20) {
            return array('status' => -9, 'msg' => '购物车最多只能放20种商品', 'result' => '');
        }
        $result = $this->addNormalCart($goods_num, $goods_spec_key, $status);
        //$result['result'] = $this->getUserCartGoodsNum(); // 查找购物车数量
        return $result;
    }

    /**
     * modify ：订餐购物车
     * @param $goods_num|购买商品数量
     * @param $goods_spec_key|购买商品规格
     * @return array
     */
    public function addGoodsToCart2($goods_num, $goods_spec_key, $status=0){
        if(empty($this->goods)){
            return ['status'=>'-3','msg'=>'购买商品不存在','result'=>''];
        }
        $userCartCount = Db::name('meal_cart')->where(['user_id'=>$this->user_id])->count();//获取用户购物车的商品有多少种
        if ($userCartCount >= 20) {
            return array('status' => -9, 'msg' => '购物车最多只能放20种商品', 'result' => '');
        }
        $result = $this->addNormalCart2($goods_num, $goods_spec_key, $status);
        return $result;
    }



    /**
     * 购物车添加普通商品
     * @param $goods_num|购买的商品数量
     * @param $goods_spec_key|购买的商品规格
     * @return array
     */
    private function addNormalCart($goods_num,$goods_spec_key, $status = 0){
        $CartModel = new Cart();
        $store_count = $this->goods['store_count'];
        // 获取商品对应的规格价钱 库存 条码
        $specGoodsPriceList = M('SpecGoodsPrice')->where("goods_id", $this->goods['goods_id'])->cache(true, MT_CACHE_TIME)->getField("key,key_name,price,store_count");
        if(!empty($specGoodsPriceList)){
            $specPrice = $specGoodsPriceList[$goods_spec_key]['price']; // 获取规格指定的价格
            $store_count = $specGoodsPriceList[$goods_spec_key]['store_count'];
        }
        // 查询购物车是否已经存在这商品
        $userCartGoods = $CartModel::get(['user_id'=>$this->user_id,'goods_id'=>$this->goods['goods_id'],'spec_key'=>$goods_spec_key]);
        // 如果该商品已经存在购物车
        if ($userCartGoods) {
            $userWantGoodsNum = $goods_num + $userCartGoods['goods_num'];//本次要购买的数量,如要加上购物车的本身存在的数量
            if($userWantGoodsNum > $store_count){
                return array('status' => -4, 'msg' => '商品库存不足，剩余'.$store_count.',当前购物车已有'.$userCartGoods['goods_num'].'件', 'result' => '');
            }

            //没有阶梯价格，如果有规格价格，就使用规格价格，否则使用本店价。
            $price = isset($specPrice) ? $specPrice : $this->goods['shop_price'];

            $cartResult = $CartModel->save(['goods_num' => $userWantGoodsNum,'goods_price'=>$price], ['id' => $userCartGoods['id']]);
        }else{

            //没有阶梯价格，如果有规格价格，就使用规格价格，否则使用本店价。
            $price = isset($specPrice) ? $specPrice : $this->goods['shop_price'];

            $cartAddData = array(
                'user_id'  => $this->user_id,   // 用户id
                'goods_id' => $this->goods['goods_id'],   // 商品id
                'goods_sn' => $this->goods['goods_sn'],   // 商品货号
                'goods_name'  => $this->goods['goods_name'],   // 商品名称
                'goods_price' => $price,  // 购买价
                'goods_num' => $goods_num, // 购买数量
                'add_time'  => time(), // 加入购物车时间
                'selected'  => $status,
            );
            if($goods_spec_key){
                $cartAddData['spec_key'] = $goods_spec_key;
                $cartAddData['spec_key_name'] = $specGoodsPriceList[$goods_spec_key]['key_name']; // 规格 key_name
            }
            $cartResult = Db::name('Cart')->insert($cartAddData);
        }
        if($cartResult !== false){
            return array('status' => 200, 'msg' => '成功加入购物车', 'result' => '');
        }else{
            return array('status' => 500, 'msg' => '加入购物车失败', 'result' => '');
        }
    }

    //订餐购物车添加商品
    private function addNormalCart2($goods_num,$goods_spec_key, $status = 0){
        $store_count = $this->goods['store_count'];
        // 获取商品对应的规格价钱 库存 条码
        $specGoodsPriceList = M('SpecGoodsPrice')->where("goods_id", $this->goods['goods_id'])->cache(true, MT_CACHE_TIME)->getField("key,key_name,price,store_count");
        if(!empty($specGoodsPriceList)){
            $specPrice = $specGoodsPriceList[$goods_spec_key]['price']; // 获取规格指定的价格
            $store_count = $specGoodsPriceList[$goods_spec_key]['store_count'];
        }
        // 查询购物车是否已经存在这商品
        $userCartGoods = Db::name('meal_cart')->where(['user_id'=>$this->user_id,'goods_id'=>$this->goods['goods_id'],'spec_key'=>$goods_spec_key])->find();
        // 如果该商品已经存在购物车
        if ($userCartGoods) {
            $userWantGoodsNum = $goods_num + $userCartGoods['goods_num'];//本次要购买的数量,如要加上购物车的本身存在的数量
            if($userWantGoodsNum > $store_count){
                return array('status' => -4, 'msg' => '商品库存不足，剩余'.$store_count.',当前购物车已有'.$userCartGoods['goods_num'].'件', 'result' => '');
            }
            //没有阶梯价格，如果有规格价格，就使用规格价格，否则使用本店价。
            $price = isset($specPrice) ? $specPrice : $this->goods['shop_price'];
            $cartResult = Db::name('meal_cart')->where(['id' => $userCartGoods['id']])->save(['goods_num' => $userWantGoodsNum,'goods_price'=>$price], );
        }else{

            //没有阶梯价格，如果有规格价格，就使用规格价格，否则使用本店价。
            $price = isset($specPrice) ? $specPrice : $this->goods['shop_price'];

            $cartAddData = array(
                'user_id'  => $this->user_id,   // 用户id
                'goods_id' => $this->goods['goods_id'],   // 商品id
                'cat_id' => $this->goods['cat_id'],   // 商品id
                'goods_sn' => $this->goods['goods_sn'],   // 商品货号
                'goods_name'  => $this->goods['goods_name'],   // 商品名称
                'goods_price' => $price,  // 购买价
                'goods_num' => $goods_num, // 购买数量
                'add_time'  => time(), // 加入购物车时间
                'selected'  => $status,
            );
            //dump($cartAddData);
            if($goods_spec_key){
                $cartAddData['spec_key'] = $goods_spec_key;
                $cartAddData['spec_key_name'] = $specGoodsPriceList[$goods_spec_key]['key_name']; // 规格 key_name
            }
            $cartResult = Db::name('meal_cart')->insert($cartAddData);
            //dump($cartResult);die;
        }
        if($cartResult !== false){
            return array('status' => 200, 'msg' => '成功加入购物车', 'result' => '');
        }else{
            return array('status' => 500, 'msg' => '加入购物车失败', 'result' => '');
        }
    }



    /**
     * 获取用户购物车商品总数
     * @return float|int
     */
    public function getUserCartGoodsNum(){
        $goods_num = Db::name('cart')->where(['user_id' => $this->user_id])->sum('goods_num');
        return empty($goods_num) ? 0 : $goods_num;
    }

    /**
     * 获取用户的购物车列表
     * @param int $selected|是否被用户勾选中的 0 为全部 1为选中  一般没有查询不选中的商品情况
     * @return array
     */
    public function getUserCartList($selected){
        $cartWhere['user_id'] = $this->user_id;
        $cartList = DB::name('Cart')->where($cartWhere)->select();  // 获取购物车商品
        $total_goods_num = $total_price = 0;//初始化数据。商品总共数量/商品总额
        foreach ($cartList as $k => $val) {

            $cartList[$k]['goods_fee'] = $val['goods_num'] * $val['goods_price'];
            $cartList[$k]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']) ?: 0; // 最多可购买的库存数量
            $total_goods_num += $val['goods_num'];

            // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
            if ($selected == 1 && $val['selected'] == 0){
                continue;
            }
            $total_price += $val['goods_num'] * $val['goods_price'];
        }
        $num = DB::name('Cart')->where($cartWhere)->where(['selected' =>1])->count();
        $total_price = array('total_fee' => $total_price, 'num' => $num); // 总计

        return array('cartList' => $cartList, 'total_price' => $total_price);
    }


    public function getUserCartList2($selected){
        $cartWhere['user_id'] = $this->user_id;
        $cartList = DB::name('meal_cart')->where($cartWhere)->select();  // 获取购物车商品
        $total_goods_num = $total_price = 0;//初始化数据。商品总共数量/商品总额
        foreach ($cartList as $k => $val) {

            $cartList[$k]['goods_fee'] = $val['goods_num'] * $val['goods_price'];
            $cartList[$k]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']) ?: 0; // 最多可购买的库存数量
            $total_goods_num += $val['goods_num'];

            // 如果要求只计算购物车选中商品的价格 和数量  并且  当前商品没选择 则跳过
            if ($selected == 1 && $val['selected'] == 0){
                continue;
            }
            $total_price += $val['goods_num'] * $val['goods_price'];
        }
        $num = DB::name('meal_cart')->where($cartWhere)->where(['selected' =>1])->count();
        $total_price = array('total_fee' => $total_price, 'num' => $num); // 总计

        return array('cartList' => $cartList, 'total_price' => $total_price);
    }
}